package com.itboye.ihomebank.base;

import java.lang.ref.WeakReference;
import java.util.LinkedList;
import java.util.List;

import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Application;
import android.app.Notification;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.widget.RemoteViews;
import android.widget.Toast;

import com.alibaba.mobileim.YWAPI;
import com.alibaba.wxlib.util.SysUtil;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.itboye.ihomebank.R;
import com.itboye.ihomebank.bean.NotificationBean;
import com.itboye.ihomebank.constants.SPContants;
import com.itboye.ihomebank.login.LoginActivity;
import com.itboye.ihomebank.message.ActivitySystemMessage;
import com.itboye.ihomebank.myzhujia.ActivityMySign;
import com.itboye.ihomebank.util.SPUtils;
import com.umeng.message.IUmengRegisterCallback;
import com.umeng.message.PushAgent;
import com.umeng.message.UTrack;
import com.umeng.message.UmengMessageHandler;
import com.umeng.message.UmengNotificationClickHandler;
import com.umeng.message.entity.UMessage;

public class MyApplcation extends Application {

	public static MyApplcation ctx;

	private Toast toast;

	private List<WeakReference<Activity>> activityList = new LinkedList<>();

	protected String afterOpen;

	protected String activity;

	protected String extra;

	protected org.json.JSONObject jsonObject2;

	protected String afterOpen2;
	String baseUrl = "http://sunsun.itboye.com/index.php/Webview/index/systemMessage?";

	protected String order_code;

	protected String id;

	protected int type;

	protected JSONObject jsonObject;
	boolean isReadOne, isReadTwo;

	public PushAgent mPushAgent;

	public PushAgent getmPushAgent() {
		return mPushAgent;
	}

	private static RequestQueue queue;

	// private List<WeakReference<Activity>> activitys = new
	// ArrayList<WeakReference<Activity>>();

	// private UncaughtExceptionHandler exceptionHandler;
	public static MyApplcation getInstance() {
		return ctx;
	}

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		ctx = this;
		initUMengPush();
		queue = Volley.newRequestQueue(ctx);
		if (mustRunFirstInsideApplicationOnCreate()) {
			// todo 如果在":TCMSSevice"进程中，无需进行openIM和app业务的初始化，以节省内存
			return;
		}
		SysUtil.setApplication(this);
		// 初始化云旺SDK
		// InitHelper.initYWSDK(this);
		YWAPI.init(this, SPContants.YW_APPKEY);

		// YWAPI.initFeedBack(this);

	}

	private void initUMengPush() {
		mPushAgent = PushAgent.getInstance(this);
		mPushAgent.setDebugMode(true);

		// sdk开启通知声音
		// mPushAgent.setNotificationPlaySound(MsgConstant.NOTIFICATION_PLAY_SDK_ENABLE);
		// sdk关闭通知声音
		// mPushAgent.setNotificationPlaySound(MsgConstant.NOTIFICATION_PLAY_SDK_DISABLE);
		// 通知声音由服务端控制
		// mPushAgent.setNotificationPlaySound(MsgConstant.NOTIFICATION_PLAY_SERVER);

		// mPushAgent.setNotificationPlayLights(MsgConstant.NOTIFICATION_PLAY_SDK_DISABLE);
		// mPushAgent.setNotificationPlayVibrate(MsgConstant.NOTIFICATION_PLAY_SDK_DISABLE);

		UmengMessageHandler messageHandler = new UmengMessageHandler() {
			/**
			 * 自定义消息的回调方法
			 * */
			@Override
			public void dealWithCustomMessage(final Context context,
					final UMessage msg) {
				new Handler().post(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
						// 对自定义消息的处理方式，点击或者忽略
						boolean isClickOrDismissed = true;
						if (isClickOrDismissed) {
							// 自定义消息的点击统计
							UTrack.getInstance(getApplicationContext())
									.trackMsgClick(msg);
						} else {
							// 自定义消息的忽略统计
							UTrack.getInstance(getApplicationContext())
									.trackMsgDismissed(msg);
						}
						Toast.makeText(context, msg.custom, Toast.LENGTH_LONG)
								.show();
					}
				});
			}

			@Override
			public void dealWithNotificationMessage(Context arg0, UMessage arg1) {
				// TODO Auto-generated method stub
				super.dealWithNotificationMessage(arg0, arg1);
				Toast.makeText(arg0, arg1.getRaw().toString(),
						Toast.LENGTH_LONG).show();
			}

			/**
			 * 自定义通知栏样式的回调方法
			 * */
			@SuppressLint("NewApi")
			@Override
			public Notification getNotification(Context context, UMessage msg) {
				switch (msg.builder_id) {
				case 1:
					Notification.Builder builder = new Notification.Builder(
							context);
					RemoteViews myNotificationView = new RemoteViews(
							context.getPackageName(),
							R.layout.notification_view);
					myNotificationView.setTextViewText(R.id.notification_title,
							msg.title);
					myNotificationView.setTextViewText(R.id.notification_text,
							msg.text);
					myNotificationView.setImageViewBitmap(
							R.id.notification_large_icon,
							getLargeIcon(context, msg));
					myNotificationView.setImageViewResource(
							R.id.notification_small_icon,
							getSmallIconId(context, msg));
					builder.setContent(myNotificationView)
							.setSmallIcon(getSmallIconId(context, msg))
							.setTicker(msg.ticker).setAutoCancel(true);

					return builder.getNotification();
				default:
					// 默认为0，若填写的builder_id并不存在，也使用默认。
					return super.getNotification(context, msg);
				}
			}
		};
		mPushAgent.setMessageHandler(messageHandler);

		/**
		 * 自定义行为的回调处理 UmengNotificationClickHandler是在BroadcastReceiver中被调用，故
		 * 如果需启动Activity，需添加Intent.FLAG_ACTIVITY_NEW_TASK
		 * */
		UmengNotificationClickHandler notificationClickHandler = new UmengNotificationClickHandler() {
			@Override
			public void dealWithCustomAction(Context context, UMessage msg) {
				Toast.makeText(context, msg.custom, Toast.LENGTH_LONG).show();
				Toast.makeText(context, msg.custom.toString(),
						Toast.LENGTH_LONG).show();
				System.out.println(msg.custom.toString() + ">通知栏数据>");
			}

			@Override
			public void openActivity(Context arg0, UMessage arg1) {
				// TODO Auto-generated method stub
				// super.openActivity(arg0, arg1);

				Gson gson = new Gson();
				NotificationBean bean = gson.fromJson(arg1.getRaw().toString(),
						NotificationBean.class);
				Intent intent = new Intent();

				// String url =
				// "http://sunsun.itboye.com/index.php/Webview/Express/viewOrder?order_code="
				// + order_code;
				// System.out
				// .println("model.getExtra().getafterOpen().getOrderCode()"
				// + order_code);
				String uid = SPUtils.get(ctx, null, SPContants.USER_ID, "")
						+ "";
				if (uid.equals("")) {
					intent = new Intent(ctx, LoginActivity.class);
					startActivity(intent);
					return;
				}
				if (bean.getBody().getActivity().equals("system_message")) {
					intent = new Intent(ctx, ActivitySystemMessage.class);
					intent.putExtra("type", 1);
				} else if (bean.getBody().getActivity()
						.equals("contract_message")) {
					intent = new Intent(ctx, ActivityMySign.class);
					intent.putExtra("contract_no", bean.getExtra().getId());
				} else if (bean.getBody().getActivity().equals("lock_message")) {
					intent = new Intent(ctx, ActivitySystemMessage.class);
					intent.putExtra("type", 4);
				}
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivity(intent);
			}
		};
		// 使用自定义的NotificationHandler，来结合友盟统计处理消息通知
		// 参考http://bbs.umeng.com/thread-11112-1-1.html
		// CustomNotificationHandler notificationClickHandler = new
		// CustomNotificationHandler();
		mPushAgent.setNotificationClickHandler(notificationClickHandler);

		// 注册推送服务 每次调用register都会回调该接口
		mPushAgent.register(new IUmengRegisterCallback() {
			@Override
			public void onSuccess(String deviceToken) {
				System.out.println(">>>" + deviceToken);
			}

			@Override
			public void onFailure(String s, String s1) {

			}
		});

	}

	private boolean mustRunFirstInsideApplicationOnCreate() {
		// 必须的初始化
		SysUtil.setApplication(this);
		return SysUtil.isTCMSServiceProcess(getApplicationContext());
	}

	public void showNetWorkError() {
		if (toast == null) {
			toast = Toast.makeText(MyApplcation.ctx, "", 1);
			toast.setGravity(Gravity.CENTER, 0, 0);
			toast.setView(LayoutInflater.from(MyApplcation.ctx).inflate(
					R.layout.dialog_network_error, null));
		}

		toast.show();
	}

	public void addActivity(Activity activity) {
		activityList.add(new WeakReference<Activity>(activity));
	}

	// 遍历所有Activity并finish
	public void exit() {
		for (WeakReference<Activity> activity : activityList) {
			if (activity.get() != null) {
				activity.get().finish();
			}

		}
		System.exit(0);
	}

	/**
	 * @return the queue
	 */
	public static RequestQueue getQueue() {
		return queue;
	}

	public static <T> void addRequest(Request<T> request) {
		request.addMarker("itboye");
		getQueue().add(request);
	}
}
